package com.basker.pisces.data.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.basker.pisces.data.DynamicDataSource;
import com.basker.pisces.data.execute.DynamicJdbcTemplate;
import com.basker.pisces.data.execute.SpringJdbcSqlExecutor;
import com.basker.pisces.orm.execute.ISqlExecutor;

@Configuration
@EnableTransactionManagement
@ConditionalOnClass({DynamicDataSource.class, DynamicJdbcTemplate.class})
public class JdbcConfiguration {

    /**
     * 动态数据源
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(DynamicDataSource.class)
    public DynamicDataSource dynamicDataSource() {
        return new DynamicDataSource();
    }

    /**
     * 提供事务管理器
     *
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager dynamicDataSourceTransactionManager(
            @Qualifier("dynamicDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 引用DynamicDataSource的JdbcTemplate
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(DynamicJdbcTemplate.class)
    public DynamicJdbcTemplate dynamicJdbcTemplate() {
        return new DynamicJdbcTemplate();
    }

    @Bean
    @ConditionalOnMissingBean(ISqlExecutor.class)
    public SpringJdbcSqlExecutor springJdbcSqlExecutor() {
        return new SpringJdbcSqlExecutor();
    }
}
